<?php
/**
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2017/3/16 0016
 * Time: 17:27
 */
namespace app\admin\controller;
use app\models\Models;

class Goods extends Check{
    /**
     * 商品列表
     * @return \think\response\View
     */
    public function goodsList(){
        $get = input('param.');
        $goods = new Models('goods');
        // 条件查询
        $search = search($get,'a.goods_no','a.create_time','a.status');
        $where  = $search['condition'].' and a.is_delete ='.Models::DELETE_NOT;
        // 商家登录商品列表
        $group_arr = self::getGroup();
        if($group_arr['group_id'] == Models::GROUP_BUSINESS){
            $where .= ' and a.bid = '.$group_arr['id'];
            $flag = true;
        }
        // 商家列表查询商品列表
        if($get['bid']){
            $where .= ' and a.bid = '.$get['bid'];
            $search['display']['bid'] = $get['bid'];
        }
        // 根据商品类型查询
        if($get['type_id']){
            $where .= ' and a.type_id = '.$get['type_id'];
            $search['display']['type_id'] = $get['type_id'];
        }
        $join   = [['business b','a.bid = b.id','left'],['goods_type c','a.type_id = c.id','left']];
        $field  = "a.*,b.name business,c.name type_name";
        $list = $goods->_page($where,$field,'a.id desc',$join,$get['page'],10,$get);
        // 配置url
        $config = self::getConfig();
        $pre = $config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'goods'. DS .'s';
        // 商品类型列表
        $type = new Models('goods_type');
        $goods_type = $type->_select(['status'=>Models::STATUS_ON],'id,name');
        return view('goodsList',['list'=>$list->items(),'page'=>$list->render(),'display'=>$search['display'],'pre'=>$pre,'flag'=>$flag,'type'=>$goods_type]);
    }

    /**
     * 添加商品
     * @return array|\think\response\View
     */
    public function goodsAdd(){
        // 判断商家登录
        $group_arr = self::getGroup();
        $goods = new Models('goods');
        $type = new Models('goods_type');
        if(request()->isAjax()){
            $post = input('param.');
            $ids_arr = $post['gid'];
            unset($post['gid']);
            try{
                if($group_arr['group_id'] == Models::GROUP_BUSINESS){
                    $post['bid'] = $group_arr['id'];
                    $post['bprice'] = $post['price'];
                } else {
                    $post['status'] = Models::GOODS_STATUS_ON;
                    $type_info = $type->_find($post['type_id']);
                    if($type_info['bid'] != $post['bid'] && !empty($type_info['bid'])){
                        throw new \LogicException('请选择正确的商品类型',1006);
                    }
                }
                $post['create_time'] = time();
                $post['image'] = upload('goods')[0];
                $post['goods_no'] = 'JY'.strtoupper(uniqid());
                $gid = $goods->_add($post);
                if(!$gid){
                    throw new \LogicException('操作失败',1010);
                }
                // 套餐
                if($post['type_id'] == 1){
                    if(empty($ids_arr)){
                        throw new \LogicException('套餐商品不能为空',1004);
                    }
                    $combo = new Models('goods_combo');
                    foreach($ids_arr as $v){
                        $arr['gid'] = $v;
                        $arr['cid'] = $gid;
                        $add[] = $arr;
                    }
                    $bool = $combo->_addAll($add);
                    if(!$bool){
                        throw new \LogicException('操作失败',1010);
                    }
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $where = [];
        if($group_arr['group_id'] == Models::GROUP_BUSINESS){
            $flag = $group_arr['id'];
            $where = ['a.status'=>Models::STATUS_ON,'a.bid'=>[['eq',0],['eq',$group_arr['id']],'or']];
        }
        // 商家列表
        $admin = new Models('admin');
        $business  = $admin->joinMany([['business b','a.id = b.id','right']],['a.status'=>Models::STATUS_ON,'b.id'=>['<>',Models::OFFICIAL]],'a.id,b.name');
        // 商品类型列表
        $goods_type = $type->joinMany([['business b','a.bid = b.id','left']],$where,'a.id,a.name,b.name business');
        // 商品列表,获取不是套餐的所有商品
        $goods_list = $goods->_select(['status'=>Models::GOODS_STATUS_ON,'type_id'=>['neq',1]],'id,name');
        return view('goodsAdd',['business'=>$business,'flag'=>$flag,'type'=>$goods_type,'goods_list'=>$goods_list]);
    }

    /**
     * 修改商品
     * @return array|\think\response\View
     */
    public function goodsSave(){
        // 判断商家登录
        $group_arr = self::getGroup();
        $goods = new Models('goods');
        $type = new Models('goods_type');
        if(request()->isAjax()){
            $post = input('param.');
            $ids_arr = $post['gid'];
            unset($post['gid']);
            try{
                if($group_arr['group_id'] == Models::GROUP_BUSINESS){
                    $post['bid'] = $group_arr['id'];
                } else {
                    // 非商家登录
                    $post['status'] = Models::GOODS_STATUS_ON;
                    $type_info = $type->_find($post['type_id']);
                    if($type_info['bid'] != $post['bid'] && !empty($type_info['bid'])){
                        throw new \LogicException('请选择正确的商品类型',1006);
                    }
                }
                $data = [
                    'id'=>$post['id'],
                    'bid'=>$post['bid'],
                    'name'=>$post['name'],
                    'qty'=>$post['qty'],
                    'descrip'=>$post['descrip']
                ];
                if($_FILES){
                    $data['image'] = upload('goods')[0];
                }
                $bool = $goods->_save($data);
                if(false === $bool){
                    throw new \LogicException('操作失败',1010);
                }
                // 套餐
                if($post['type_id'] == 1){
                    if(empty($ids_arr)){
                        throw new \LogicException('套餐商品不能为空',1004);
                    }
                    $combo = new Models('goods_combo');
                    $ids = $combo->getColumn(['cid'=>$post['id']],'gid');
                    // 判断套餐内容是否更改
                    if($ids != $ids_arr){
                        // 套餐内容有更改，先删除之前套餐，再重新插入套餐
                        $bool = $combo->_delete(['cid'=>$post['id']]);
                        foreach($ids_arr as $v){
                            $arr['gid'] = $v;
                            $arr['cid'] = $post['id'];
                            $add[] = $arr;
                        }
                        $bool1 = $combo->_addAll($add);
                        if(!$bool || !$bool1){
                            throw new \LogicException('操作失败',1010);
                        }
                    }
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $where = [];
        if($group_arr['group_id'] == Models::GROUP_BUSINESS){
            $flag = true;
            $where = ['a.status'=>Models::STATUS_ON,'a.bid'=>[['eq',0],['eq',$group_arr['id']],'or']];
        }
        $get = input('param.');
        $info = $goods->_find($get['id']);
        $config = self::getConfig();
        $pre = $config['http'].$_SERVER['HTTP_HOST']. DS .'uploads'. DS .'goods'. DS .'s';
        // 商家列表
        $admin = new Models('admin');
        $business = $admin->joinMany([['business b','a.id = b.id','right']],['a.status'=>Models::STATUS_ON,'b.id'=>['<>',Models::OFFICIAL]],'a.id,b.name');
        // 商品类型列表
        $goods_type = $type->joinMany([['business b','a.bid = b.id','left']],$where,'a.id,a.name,b.name business');
        // 商品列表,获取非套餐的所有商品
        $goods_list = $goods->_select(['status'=>Models::GOODS_STATUS_ON,'type_id'=>['neq',1]],'id,name');
        // 获取套餐商品id
        $combo = new Models('goods_combo');
        $combo_ids = $combo->getColumn(['cid'=>$get['id']],'gid');
        return view('goodsSave',['info'=>$info,'business'=>$business,'type'=>$goods_type,'pre'=>$pre,'flag'=>$flag,'goods_list'=>$goods_list,'goods_combo'=>$combo_ids]);
    }

    /**
     * 删除商品
     * @return array
     */
    public function goodsDel(){
        if(request()->isAjax()){
            $post = input('param.');
            $goods = new Models('goods');
            try{
                $bool = $goods->setValue(['id'=>$post['id']],['is_delete'=>Models::DELETE_YES]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
    }

    /**
     * 修改价格
     * @return array
     */
    public function price(){
        $goods = new Models('goods');
        if(request()->isAjax()){
            $post = input('param.');
            try{
                $bool = $goods->setValue(['id'=>$post['id']],['price'=>$post['price']]);
                if(false === $bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
        $get = input('param.');
        $info = $goods->_find($get['id']);
        return view('price',['info'=>$info]);
    }

    /**
     * 套餐管理
     * @return array
     */
    public function combo(){
        $combo = new Models('goods_combo');
        $get = input('param.');
        $list = $combo->joinMany([['goods b','a.gid = b.id','left']],['a.cid'=>$get['id']],'a.id,b.id gid,b.name,a.qty');
        return view('combo',['list'=>$list]);
    }

    /**
     * 删除套餐
     * @return array
     */
    public function comboDel(){
        if(request()->isAjax()){
            $post = input('param.');
            $goods = new Models('goods_combo');
            try{
                $bool = $goods->_delete(['id'=>$post['id']]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
    }

    /**
     * 设置套餐商品数量
     * @return array
     */
    public function comboQty(){
        if(request()->isAjax()){
            $post = input('param.');
            $goods = new Models('goods_combo');
            try{
                $bool = $goods->_save(['id'=>$post['id'],'qty'=>$post['qty']]);
                if(false === $bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
    }

    /**
     * 审核通过
     * @return array
     */
    public function pass(){
        if(request()->isAjax()){
            $post = input('param.');
            $goods = new Models('goods');
            try{

                $bool = $goods->_save(['id'=>$post['id'],'status'=>Models::GOODS_STATUS_ON]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
    }

    /**
     * 审核拒绝
     * @return array
     */
    public function nopass(){
        if(request()->isAjax()){
            $post = input('param.');
            $goods = new Models('goods');
            try{
                $bool = $goods->_save(['id'=>$post['id'],'status'=>Models::GOODS_AUDIT_NOPASS]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
    }

    /**
     * 启用
     * @return array
     */
    public function start(){
        if(request()->isAjax()){
            $post = input('param.');
            $goods = new Models('goods');
            try{
                $bool = $goods->setValue(['id'=>$post['id']],['status'=>Models::GOODS_STATUS_ON]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
    }

    /**
     * 停用
     * @return array
     */
    public function stop(){
        if(request()->isAjax()){
            $post = input('param.');
            $goods = new Models('goods');
            try{
                $bool = $goods->setValue(['id'=>$post['id']],['status'=>Models::GOODS_STATUS_OFF]);
                if(!$bool){
                    throw new \LogicException('操作失败',1010);
                }
            } catch (\Exception $e){
                return self::formatResult($e->getCode(),$e->getMessage());
            }
            return self::formatSuccessResult();
        }
    }
}